<template>
  <view class="box" v-for="(item, index) in list" :key="index">
    <uv-image
        width="80"
        height="80"
        :src="item.goods_img"
    ></uv-image>
    <view class="info">
      <view class="name">
        {{ item.goods_name }}
      </view>
      <view class="bottom">
        <view class="price">
          ￥{{ item.goods_price }}
        </view>
        <view class="num">
          X 1
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, defineProps, computed, defineEmits, watch } from "vue";
import { GoodList } from "@/request/api";

const emit = defineEmits(); // 定义 emit 函数
const list = ref([]);
const props = defineProps({
  id: {
    type: String,
    required: true
  }
});
const pageNum = ref(1);

// 根据 id 获取商品
const fetchGoodsById = async (id) => {
  try {
    const initialRes = await GoodList({ pageNum: pageNum.value, pageSize: 10 });
    if (initialRes.code === 0) {
      const total = initialRes.result.total;
      const allGoodsRes = await GoodList({ pageNum: pageNum.value, pageSize: total });
      if (allGoodsRes && allGoodsRes.code === 0) {
        const goods = allGoodsRes.result.list;

        const filteredGoods = goods.filter(item => {
          return item.id === Number(props.id);
        });

        console.log(filteredGoods, '---1'); // 查看过滤后的结果
        return filteredGoods; // 返回过滤后的商品
      }
    } else {
      console.error(initialRes.msg);
    }
  } catch (err) {
    console.error('获取商品列表失败', err);
  }
  return [];
};

onMounted(async () => {
  list.value = await fetchGoodsById(props.id); // 根据 id 获取商品
  console.log(props.id, '====')
  console.log(list.value, '---')
  emit('update:list', list.value); // Emit 商品列表
  emit('update:totalPrice', totalPrice.value); // Emit 总价格
});

const totalPrice = computed(() => {
  return list.value.reduce((total, item) => {
    return total + (parseFloat(item.goods_price) * item.number);
  }, 0).toFixed(2);
});

// 监听 list 或 totalPrice 的变化并 emit
watch([list, totalPrice], ([newList, newTotalPrice]) => {
  emit('update:list', newList);
  emit('update:totalPrice', newTotalPrice);
});
</script>

<style scoped lang="scss">
.box {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #FFFFFF;
  border-radius: 15px;
  margin-top: 10px;
  .info {
    margin-left: 15px;
    width: calc(100% - 95px);
    .name {
      display: -webkit-box; /* 这是创建一个伸缩容器 */
      -webkit-box-orient: vertical; /* 定义伸缩容器的主轴方向 */
      -webkit-line-clamp: 2; /* 限制显示的行数为2行 */
      overflow: hidden; /* 隐藏超出内容 */
      text-overflow: ellipsis; /* 使用省略号表示溢出的文本 */
    }
    .bottom {
      margin-top: 10px;
      display: flex;
      justify-content: space-between;
      width: 100%;
      align-items: center;
      .price {
        color: red;
      }
    }
  }
}
</style>